package com.jianli.smart.aop.demo;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jianli.smart.aop.Proxy;
import com.jianli.smart.aop.ProxyChain;
import com.jianli.smart.aop.annotation.Aspect;
import com.jianli.smart.aop.annotation.Transaction;
import com.jianli.smart.core.annotation.Controller;
import com.jianli.smart.dao.DatabaseHelper;

@Aspect(Controller.class)
public class TranscationProxy implements Proxy{
	private static final Logger LOGGER = LoggerFactory.getLogger(TranscationProxy.class);

	@Override
	public Object doProxy(ProxyChain proxyChain) throws Throwable {
		Object result;
		Method method = proxyChain.getTargetMethod();
		if(method.isAnnotationPresent(Transaction.class)){
			try{
				DatabaseHelper.beginTranscation();
				result = proxyChain.doProxyChain();
				DatabaseHelper.commitTranscation();
			} catch (Exception e){
				LOGGER.error("事务方法发生异常，执行回滚",e);
				DatabaseHelper.rollBack();
				throw e;
			}
			
		}else{
			result = proxyChain.doProxyChain();
		}
		return result;
	}
	
}
